const fs = require('fs')
const path = require('path')
const { JSDOM } = require('jsdom')

// Get file path from command line argument
const filePath =
  '/Users/zhangman/code/recsteel/recsteel.saas.all_in_one/app/src/main/assets/index.html'

// Read the HTML file
fs.readFile(filePath, 'utf8', (err, html) => {
  if (err) {
    console.error('Error reading file:', err)
    return
  }

  // Parse the HTML
  const dom = new JSDOM(html)
  const document = dom.window.document

  // Remove all scripts in head
  const headScripts = document.head.querySelectorAll('script')
  headScripts.forEach((script) => script.remove())

  // Remove first script in body
  const bodyScripts = document.body.querySelectorAll('script')
  if (bodyScripts.length > 0) {
    bodyScripts[0].remove()
  }

  // Process remaining scripts in body
  const remainingScripts = document.body.querySelectorAll('script')
  remainingScripts.forEach((script) => {
    // Remove crossorigin and nomodule attributes
    script.removeAttribute('crossorigin')
    script.removeAttribute('nomodule')

    // Replace data-src with src if it exists
    if (script.hasAttribute('data-src')) {
      const dataSrc = script.getAttribute('data-src')
      script.removeAttribute('data-src')
      script.setAttribute('src', dataSrc)
    }

    // Remove script content
    script.textContent = ''
  })

  const links = document.querySelectorAll('link')
  links.forEach((link) => {
    link.removeAttribute('crossorigin')
  })
  // Serialize the modified DOM back to HTML
  const modifiedHtml = dom.serialize()

  // Write the modified HTML back to the file
  fs.writeFile(filePath, modifiedHtml, (err) => {
    if (err) {
      console.error('Error writing file:', err)
      return
    }
    console.log('File successfully processed and saved')
  })
})
